Passed
Pull Request — master (#19)
by Muhammad Dyas
01:36
created

ActionHandler.recordVote   C

Complexity

Conditions 11

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 27
rs 5.4
c 0
b 0
f 0
cc 11

How to fix   Complexity   

Complexity

Complex classes like ActionHandler.recordVote often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import {chat_v1 as chatV1} from 'googleapis/build/src/apis/chat/v1';
2
import BaseHandler from './BaseHandler';
3
import NewPollFormCard from '../cards/NewPollFormCard';
4
import {addOptionToState, getConfigFromInput, getStateFromCard} from '../helpers/state';
5
import {callMessageApi} from '../helpers/api';
6
import {createDialogActionResponse, createStatusActionResponse} from '../helpers/response';
7
import PollCard from '../cards/PollCard';
8
import {ClosableType, MessageDialogConfig, PollFormInputs, PollState, taskEvent, Voter} from '../helpers/interfaces';
9
import AddOptionFormCard from '../cards/AddOptionFormCard';
10
import {saveVotes} from '../helpers/vote';
11
import {PROHIBITED_ICON_URL} from '../config/default';
12
import ClosePollFormCard from '../cards/ClosePollFormCard';
13
import MessageDialogCard from '../cards/MessageDialogCard';
14
import {createTask} from '../helpers/task';
15
16
/*
17
This list methods are used in the poll chat message
18
 */
19
interface PollAction {
20
  saveOption(): Promise<chatV1.Schema$Message>;
21
22
  getEventPollState(): PollState;
23
}
24
25
export default class ActionHandler extends BaseHandler implements PollAction {
26
  async process(): Promise<chatV1.Schema$Message> {
27
    const action = this.event.common?.invokedFunction;
28
    switch (action) {
29
      case 'start_poll':
30
        return await this.startPoll();
31
      case 'vote':
32
        return this.recordVote();
33
      case 'add_option_form':
34
        return this.addOptionForm();
35
      case 'add_option':
36
        return await this.saveOption();
37
      case 'show_form':
38
        const pollForm = new NewPollFormCard({topic: '', choices: []}, this.getUserTimezone()).create();
39
        return createDialogActionResponse(pollForm);
40
      case 'new_poll_on_change':
41
        return this.newPollOnChange();
42
      case 'close_poll_form':
43
        return this.closePollForm();
44
      case 'close_poll':
45
        return await this.closePoll();
46
      default:
47
        return createStatusActionResponse('Unknown action!', 'UNKNOWN');
48
    }
49
  }
50
51
  /**
52
   * Handle the custom start_poll action.
53
   *
54
   * @returns {object} Response to send back to Chat
55
   */
56
  async startPoll() {
57
    // Get the form values
58
    const formValues: PollFormInputs = this.event.common!.formInputs! as PollFormInputs;
59
60
    const config = getConfigFromInput(formValues);
61
    if (config.closedTime) {
62
      // because previously we marked up the time with user timezone offset
63
      config.closedTime -= this.getUserTimezone()?.offset ?? 0;
64
    }
65
66
    if (!config.topic || config.choices.length === 0) {
67
      // Incomplete form submitted, rerender
68
      const dialog = new NewPollFormCard(config, this.getUserTimezone()).create();
69
      return createDialogActionResponse(dialog);
70
    }
71
    const pollCard = new PollCard({
72
      author: this.event.user,
73
      ...config,
74
    }).createCardWithId();
75
    // Valid configuration, make the voting card to display in the space
76
    const message = {
77
      cardsV2: [pollCard],
78
    };
79
    const request = {
80
      parent: this.event.space?.name,
81
      requestBody: message,
82
    };
83
    const apiResponse = await callMessageApi('create', request);
84
    if (apiResponse?.data?.name) {
85
      console.log(JSON.stringify(apiResponse.data));
86
      console.log(JSON.stringify(config));
87
      if (config.autoclose && config.closedTime) {
88
        console.log('Creating task');
89
        const taskPayload: taskEvent = {'id': apiResponse.data.name, 'action': 'close_poll', 'type': 'TASK'};
90
        await createTask(JSON.stringify(taskPayload), config.closedTime);
91
      }
92
      return createStatusActionResponse('Poll started.', 'OK');
93
    } else {
94
      return createStatusActionResponse('Failed to start poll.', 'UNKNOWN');
95
    }
96
  }
97
98
  /**
99
   * Handle the custom vote action. Updates the state to record
100
   * the user's vote then rerenders the card.
101
   *
102
   * @returns {object} Response to send back to Chat
103
   */
104
  recordVote() {
105
    const parameters = this.event.common?.parameters;
106
    if (!(parameters?.['index'])) {
107
      throw new Error('Index Out of Bounds');
108
    }
109
    const choice = parseInt(parameters['index']);
110
    const userId = this.event.user?.name ?? '';
111
    const userName = this.event.user?.displayName ?? '';
112
    const voter: Voter = {uid: userId, name: userName};
113
    const state = this.getEventPollState();
114
115
    // Add or update the user's selected option
116
    state.votes = saveVotes(choice, voter, state.votes!, state.anon);
117
    const card = new PollCard(state);
118
    return {
119
      thread: this.event.message?.thread,
120
      actionResponse: {
121
        type: 'UPDATE_MESSAGE',
122
      },
123
      cardsV2: [card.createCardWithId()],
124
    };
125
  }
126
127
  /**
128
   * Opens and starts a dialog that allows users to add details about a contact.
129
   *
130
   * @returns {object} open a dialog.
131
   */
132
  addOptionForm() {
133
    const state = this.getEventPollState();
134
    const dialog = new AddOptionFormCard(state).create();
135
    return createDialogActionResponse(dialog);
136
  };
137
138
  /**
139
   * Handle add new option input to the poll state
140
   * the user's vote then rerenders the card.
141
   *
142
   * @returns {object} Response to send back to Chat
143
   */
144
  async saveOption(): Promise<chatV1.Schema$Message> {
145
    const userName = this.event.user?.displayName ?? '';
146
    const state = this.getEventPollState();
147
    const formValues = this.event.common?.formInputs;
148
    const optionValue = formValues?.['value']?.stringInputs?.value?.[0]?.trim() || '';
149
    addOptionToState(optionValue, state, userName);
150
151
    const cardMessage = new PollCard(state).createMessage();
152
153
    const request = {
154
      name: this.event.message!.name,
155
      requestBody: cardMessage,
156
      updateMask: 'cardsV2',
157
    };
158
    const apiResponse = await callMessageApi('update', request);
159
    if (apiResponse) {
160
      return createStatusActionResponse('Option is added', 'OK');
161
    } else {
162
      return createStatusActionResponse('Failed to add option.', 'UNKNOWN');
163
    }
164
  }
165
166
  getEventPollState(): PollState {
167
    const stateJson = getStateFromCard(this.event);
168
    if (!stateJson) {
169
      throw new ReferenceError('no valid state in the event');
170
    }
171
    return JSON.parse(stateJson);
172
  }
173
174
  async closePoll(): Promise<chatV1.Schema$Message> {
175
    const state = this.getEventPollState();
176
    state.closedTime = Date.now();
177
    const cardMessage = new PollCard(state).createMessage();
178
    const request = {
179
      name: this.event.message!.name,
180
      requestBody: cardMessage,
181
      updateMask: 'cardsV2',
182
    };
183
    const apiResponse = await callMessageApi('update', request);
184
    if (apiResponse) {
185
      return createStatusActionResponse('Poll is closed', 'OK');
186
    } else {
187
      return createStatusActionResponse('Failed to close poll.', 'UNKNOWN');
188
    }
189
  }
190
191
  closePollForm() {
192
    const state = this.getEventPollState();
193
    if (state.type === ClosableType.CLOSEABLE_BY_ANYONE || state.author!.name === this.event.user?.name) {
194
      return createDialogActionResponse(new ClosePollFormCard().create());
195
    }
196
197
    const dialogConfig: MessageDialogConfig = {
198
      title: 'Sorry, you can not close this poll',
199
      message: `The poll setting restricts the ability to close the poll to only the creator(${state.author!.displayName}).`,
200
      imageUrl: PROHIBITED_ICON_URL,
201
    };
202
    return createDialogActionResponse(new MessageDialogCard(dialogConfig).create());
203
  }
204
205
  newPollOnChange() {
206
    const formValues: PollFormInputs = this.event.common!.formInputs! as PollFormInputs;
207
    const config = getConfigFromInput(formValues);
208
    return createDialogActionResponse(new NewPollFormCard(config, this.getUserTimezone()).create());
209
  }
210
}
211